package com.lawrence.common.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 * @author wanglanglang
 */
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 拦截器开始时执行的方法
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("拦截器开始执行");
        //默认值为false，代表不继续往后执行。如果为true，即使拦截了也依然会执行被拦截请求对应的controller层对应的方法。
        // 因此为true和没加拦截没区别
        // 为false的话，被拦截的请求不会被执行它对应的controller方法
//        return false;
        return true;
    }

    /**
     * 拦截器结束时执行的方法
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器 结束执行 ");
    }

    /**
     * 无论拦截器是否有异常都执行的方法
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("无论是否有异常拦截器都执行");
    }

}
